""" 
生成配对的公钥密钥:
cd key
./key1_openssl_生成公钥密钥.sh
"""

from Crypto.PublicKey import RSA
from Crypto.Cipher import PKCS1_OAEP
from Crypto.Signature import pkcs1_15
from Crypto.Hash import SHA256
import base64


# 提取公钥和密钥
def get_RSA_key_by_file(private_file, public_file):
    # with open(private_file, 'rb') as f:
    #     private_key = RSA.import_key(f.read())
    # with open(public_file, 'rb') as f:
    #     public_key = RSA.import_key(f.read())
    with open(private_file, "rb") as f:
        private_key = f.read()
    with open(public_file, "rb") as f:
        public_key = f.read()
    return private_key, public_key


# RSA加密
def rsa_encrypt(public_key, data):
    recipient_key = RSA.import_key(public_key)
    cipher_rsa = PKCS1_OAEP.new(recipient_key)
    encrypted_data = cipher_rsa.encrypt(data)
    return encrypted_data


# RSA解密
def rsa_decrypt(private_key, data):
    private_key = RSA.import_key(private_key)
    cipher_rsa = PKCS1_OAEP.new(private_key)
    decrypted_data = cipher_rsa.decrypt(data)
    return decrypted_data


private_key, public_key = get_RSA_key_by_file(
    "key/private_key.pem", "key/public_key.pem"
)
data = b"Hello, World! This is RSA test msg"
encrypt_data = rsa_encrypt(public_key, data)
decrypt_data = rsa_decrypt(private_key, encrypt_data)

print("加密数据: ", encrypt_data)
print("解密数据: ", decrypt_data)
print("数据是否一致:", data == decrypt_data)
